package cn.jilian.meta.handler.support;

import java.io.IOException;

import org.apache.commons.lang3.StringUtils;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import cn.jilian.meta.handler.domain.Function;

public class FunctionSerializer extends JsonSerializer<Function> {

	@Override
	public void serialize(Function value, JsonGenerator gen, SerializerProvider serializers)
			throws IOException, JsonProcessingException {
		StringBuilder sb=new StringBuilder("function");
		if(StringUtils.isNotBlank(value.getName())) {
			sb.append(" ")
			.append(value.getName());
		}
		if(value.getParams()==null||value.getParams().isEmpty()) {
			sb.append("(){");
		}else {
			sb.append("(")
			.append(StringUtils.join(value.getParams(),","))
			.append("){");
		}
		sb.append("\r\n");
		sb.append("        ")
		.append(value.getBody())
		.append("\r\n    }");
		gen.writeRawValue(sb.toString());
	}

}
